<?php
class _sql
{
	private $db_host;
	private $db_user;
	private $db_pass;
	private $db_name;
	private $_tab_pref;
	private $_rl;
	
	public $tab_pref;
	
    public function __construct($top,$parent)
    {
    	unset($this->tab_pref);
    	
    	if ($top->_config === NULL) {
    		throw new $top->Utils->PushError("Config file not set","Не установлен файл конфигурации");
    	}
    	
    	$this->db_host = $top->_config->db->db->params->host;
    	$this->db_user = $top->_config->db->db->params->username;
    	$this->db_pass = $top->_config->db->db->params->password;
    	$this->db_name = $top->_config->db->db->params->dbname;
    	$this->_tab_pref = $top->_config->db->db->params->tabpref;
    	
        $this->connect();
    }
    
    public function __destruct() {
    	$this->disconnect();
    }
    
    private function connect()
    {
        $this->_rl = mysql_connect($this->db_host , $this->db_user , $this->db_pass);
	mysql_set_charset('utf8',$this->_rl); 
        mysql_select_db($this->db_name, $this->_rl);
    }
    
    private function disconnect()
    {
    	mysql_close($this->_rl);
    }
    
    public function exe($select) 
	{	
		return $this->exe2Db($this->db_name ,$select);
	}
	
	private function exe2Db($db,$select,$result_type = "array") 
	{	
		$retVal = array();
		mysql_select_db($db, $this->_rl);
		$query_cur = mysql_query($select,$this->_rl);
		if (!$query_cur) {
		    die('Invalid query: ' . mysql_error());
		}

		switch ($result_type) {
			case "array":
				while ($query = mysql_fetch_array($query_cur))
					$retVal[] = $query;
		
				break;
		
			case "assoc":
				while ($query = mysql_fetch_assoc($query_cur))
					$retVal[] = $query;
				break;
				
			case "object":
				while ($query = mysql_fetch_object($query_cur))
					$retVal[] = $query;
				break;
				 
			default:
				break;
		}
		
	return $retVal;
	}
	
	public function exeDummy($select) 
	{
		$this->exeDummy2Db($this->db_name,$select);
	}
	
	public function exeDummy2Db($db,$select) 
	{	
		mysql_select_db($db, $this->_rl);
		mysql_query($select,$this->_rl);
	}

	/**
	 * Returns LAST_INSERT_ID after row inser
	 *
	 * @return integer
	 */
	public function last_insert_id() {
		return mysql_insert_id($this->_rl);
	}
    
	public function __get($param) {
		if ($param=='tab_pref') {
			return $this->_tab_pref;
		} 
	}
	
	
    public function __sleep()
    {
        return array($this->db_host , $this->db_user , $this->db_pass , $this->db_name);
    }
    
    public function __wakeup()
    {
        $this->connect();
    }
}
?>